<?php

namespace App\Services;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class OpenAIService
{
    private $client;
    private $apiKey;
    private $defaultModel = 'gpt-3.5-turbo';

    public function __construct()
    {
        $this->apiKey = config('services.openai.api_key');
        $this->client = new Client([
            'base_uri' => 'https://api.openai.com/v1/',
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'timeout' => 30,
        ]);
    }

    /**
     * 生成AI角色回复
     */
    public function generateCharacterResponse($characterPrompt, $scenarioContext, array $conversationHistory, $difficultyLevel = 1)
    {
        try {
            $systemPrompt = $this->buildSystemPrompt($characterPrompt, $scenarioContext, $difficultyLevel);
            $messages = $this->buildMessageHistory($systemPrompt, $conversationHistory);

            $response = $this->client->post('chat/completions', [
                'json' => [
                    'model' => $this->defaultModel,
                    'messages' => $messages,
                    'temperature' => $this->calculateTemperature($difficultyLevel),
                    'max_tokens' => 200,
                ]
            ]);

            $data = json_decode($response->getBody()->getContents(), true);

            Log::info('OpenAI API call successful', [
                'usage' => $data['usage'] ?? null,
                'model' => $this->defaultModel
            ]);

            return [
                'message' => $data['choices'][0]['message']['content'] ?? '',
                'usage' => $data['usage'] ?? null
            ];

        } catch (\Exception $e) {
            Log::error('OpenAI API call failed', [
                'error' => $e->getMessage(),
                'difficulty_level' => $difficultyLevel
            ]);

            // 返回默认回复
            return [
                'message' => $this->getDefaultResponse($difficultyLevel),
                'usage' => null,
                'error' => true
            ];
        }
    }

    /**
     * 分析消息情感
     */
    public function analyzeSentiment($message)
    {
        try {
            $prompt = "请分析以下消息的情感倾向，返回0-100的情感分数（0=非常负面，100=非常正面）和情感类型。只返回数字分数和情感类型，用逗号分隔：\n\n" . $message;

            $response = $this->client->post('chat/completions', [
                'json' => [
                    'model' => $this->defaultModel,
                    'messages' => [
                        ['role' => 'system', 'content' => '你是一个情感分析专家，请准确分析文本情感。'],
                        ['role' => 'user', 'content' => $prompt]
                    ],
                    'temperature' => 0.1,
                    'max_tokens' => 50,
                ]
            ]);

            $data = json_decode($response->getBody()->getContents(), true);
            $result = $data['choices'][0]['message']['content'] ?? '50,neutral';

            return $this->parseSentimentResponse($result);

        } catch (\Exception $e) {
            Log::error('Sentiment analysis failed', [
                'error' => $e->getMessage(),
                'message' => $message
            ]);

            // 返回默认情感分析
            return [
                'score' => 50,
                'type' => 'neutral'
            ];
        }
    }

    /**
     * 构建系统提示词
     */
    private function buildSystemPrompt($characterPrompt, $scenarioContext, $difficultyLevel)
    {
        $difficultyInstructions = $this->getDifficultyInstructions($difficultyLevel);
        
        return "你是一个AI角色扮演助手。\n\n" .
               "角色设定：{$characterPrompt}\n\n" .
               "场景背景：{$scenarioContext}\n\n" .
               "难度要求：{$difficultyInstructions}\n\n" .
               "请严格按照角色设定进行对话，保持角色一致性。回复要简洁自然，不超过100字。";
    }

    /**
     * 构建对话历史
     */
    private function buildMessageHistory($systemPrompt, array $conversationHistory)
    {
        $messages = [
            ['role' => 'system', 'content' => $systemPrompt]
        ];

        foreach ($conversationHistory as $msg) {
            $role = $msg['sender_type'] === 'user' ? 'user' : 'assistant';
            $messages[] = ['role' => $role, 'content' => $msg['message']];
        }

        return $messages;
    }

    /**
     * 计算温度参数
     */
    private function calculateTemperature($difficultyLevel)
    {
        // 难度越高，AI回复越不可预测
        $temperatures = [
            1 => 0.3,  // 新手：较为固定的回复
            2 => 0.5,  // 初级：稍有变化
            3 => 0.7,  // 中级：适度变化
            4 => 0.8,  // 高级：较大变化
            5 => 0.9   // 专家：高度不可预测
        ];

        return $temperatures[$difficultyLevel] ?? 0.7;
    }

    /**
     * 获取难度指令
     */
    private function getDifficultyInstructions($difficultyLevel)
    {
        $instructions = [
            1 => '保持友好和耐心，给予积极回应，帮助用户建立信心。',
            2 => '适度友好，偶尔提出轻微挑战，引导用户深入对话。',
            3 => '保持中性态度，根据用户表现调整回应，适度考验用户技巧。',
            4 => '稍显挑剔，对用户回复有一定要求，需要用户展现更好的社交技巧。',
            5 => '严格要求，对不当回复表现冷淡或不满，需要用户展现高超的社交能力。'
        ];

        return $instructions[$difficultyLevel] ?? $instructions[3];
    }

    /**
     * 解析情感分析结果
     */
    private function parseSentimentResponse($response)
    {
        $parts = explode(',', trim($response));
        $score = isset($parts[0]) ? (int)trim($parts[0]) : 50;
        $type = isset($parts[1]) ? trim($parts[1]) : 'neutral';

        // 确保分数在有效范围内
        $score = max(0, min(100, $score));

        return [
            'score' => $score,
            'type' => $type
        ];
    }

    /**
     * 获取默认回复
     */
    private function getDefaultResponse($difficultyLevel)
    {
        $responses = [
            1 => '我理解你的想法，请继续说下去。',
            2 => '嗯，有意思，你还有什么想法吗？',
            3 => '我需要想想你说的话。',
            4 => '这个话题有点复杂呢。',
            5 => '我觉得我们的想法不太一样。'
        ];

        return $responses[$difficultyLevel] ?? $responses[3];
    }
}